package model.handler;

import java.util.HashMap;
import java.util.Map;

import java.util.List;

import model.Executable;
import model.GameClock;
import model.entity.Avatar;
import model.entity.BasicEntity;
import model.entity.Entity;
import model.entity.Mountable;
import model.entity.stats.StatType;
import model.interactionhandler.InteractionContainer;
import model.item.Item;
import model.map.AreaEffect;
import model.map.Direction;
import model.map.GameMap;
import model.map.HexLocationProjection;
import model.map.Location;
import model.map.LocationProjection;
import model.map.MovementType;
import model.map.Terrain;
import model.map.World;
import model.resource.AvatarMount;
import main.Log;
import utilities.*;

public class AreaEffectHandler implements Archiveable {

	private static AreaEffectHandler instance = null;
	private World world = World.getInstance();
	private GameMap gameMap = world.getCurrentMap();
	private List<BasicEntity> basicEntityList = gameMap.getEntities();

	private long delay;
	private AreaEffect areaEffect; 
	private Executable ex;

	public static AreaEffectHandler getInstance() {
		if( instance != null ) { return instance; }
		return instance = new AreaEffectHandler();
	}
	
	private AreaEffectHandler() {
		// possibly add more to this later
		this.delay = 40;
	}

	public void start(){
		//sched game clock
		ex = new Executable(){
			public void execute() {
				// de shiz!
				applyEffect();
			}
		};
		GameClock.getInstance().scheduleAtFixedRate( delay, ex);
	} 

	public void stop(){
		if(ex == null){return ;}
		GameClock.getInstance().remove(ex);
	}

	private void applyEffect(){
		for(BasicEntity e : basicEntityList) {
			Location entLocation = e.getLocation();
			if( gameMap.hasAreaEffect(entLocation) ){
				areaEffect = gameMap.getAreaEffect(entLocation);
				areaEffect.doEffect(e);
			}
		}
	}

	@Override
		public String toString(){
			return super.toString() + "AreaEffect [effect=" + areaEffect + "]";
		}
	
	public Archive save() {
		Archive archive = ArchiveFactory.createArchive();
		
		archive.putAttribute("delay", Long.toString(this.delay));
		
		archive.putClassName("areaEffect", this.areaEffect.getClass().getName());
		archive.putOneRelationship("areaEffect", this.areaEffect);
		
		return archive;
	}
	
	public void load(Archive archive) {
		this.delay = Long.parseLong(archive.getAttribute("delay"));
		
		this.areaEffect = (AreaEffect)ModelFactory.getInstance().createInstanceWithClassName(archive.getClassName("areaEffect"));
		this.areaEffect.load(archive.getOneRelationship("areaEffect"));
	}
	
}
